{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Finance Agent Tool Spec\n",
    "\n",
    "This tool connects to various open finance apis and libraries to gather news, earnings information and doing fundamental analysis.\n",
    "\n",
    "To use this tool, you'll need a few API keys:\n",
    "\n",
    "- POLYGON_API_KEY -- <https://polygon.io/>\n",
    "- FINNHUB_API_KEY -- <https://finnhub.io/>\n",
    "- ALPHA_VANTAGE_API_KEY -- <https://www.alphavantage.co/>\n",
    "- NEWSAPI_API_KEY -- <https://newsapi.org/>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Installation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install llama-index-tools-finance"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Usage"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.agent.openai import OpenAIAgent\n",
    "from llama_index.llms.openai import OpenAI\n",
    "from llama_index.tools.finance import FinanceAgentToolSpec\n",
    "\n",
    "POLYGON_API_KEY = \"\"\n",
    "FINNHUB_API_KEY = \"\"\n",
    "ALPHA_VANTAGE_API_KEY = \"\"\n",
    "NEWSAPI_API_KEY = \"\"\n",
    "OPENAI_API_KEY = \"\"\n",
    "\n",
    "GPT_MODEL_NAME = \"gpt-4-0613\"\n",
    "\n",
    "\n",
    "def create_agent(\n",
    "    polygon_api_key: str,\n",
    "    finnhub_api_key: str,\n",
    "    alpha_vantage_api_key: str,\n",
    "    newsapi_api_key: str,\n",
    "    openai_api_key: str,\n",
    ") -> OpenAIAgent:\n",
    "    tool_spec = FinanceAgentToolSpec(\n",
    "        polygon_api_key, finnhub_api_key, alpha_vantage_api_key, newsapi_api_key\n",
    "    )\n",
    "    llm = OpenAI(temperature=0, model=GPT_MODEL_NAME, api_key=openai_api_key)\n",
    "    return OpenAIAgent.from_tools(tool_spec.to_tool_list(), llm=llm, verbose=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "agent = create_agent(\n",
    "    POLYGON_API_KEY,\n",
    "    FINNHUB_API_KEY,\n",
    "    ALPHA_VANTAGE_API_KEY,\n",
    "    NEWSAPI_API_KEY,\n",
    "    OPENAI_API_KEY,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "response = agent.chat(\"What happened to AAPL stock on February 19th, 2024?\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "llama-index-4aB9_5sa-py3.10",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
